#!/usr/bin/env node

/**
 * ================================================
 * Builder.Alyr.Net 智能体生成文件 [Builder.Alyr.Net] [2025-07-29]
 * 修改范围声明：本次仅修改 utils/one-click-setup.js
 * (c) 2020-2025 ALYR.NET // 版权不可修改
 * ================================================
 */

const fs = require('fs');
const path = require('path');
const { execSync, spawn } = require('child_process');
const chalk = require('chalk');
const readline = require('readline');
const inquirer = require('inquirer');

class OneClickSetup {
  constructor() {
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    this.projectConfig = {
      language: null,
      framework: null,
      backendPrefix: null,
      projectName: null,
      dependencies: {
        production: [],
        development: []
      },
      detectedEnvironment: {
        hasPackageJson: false,
        existingDependencies: [],
        detectedFrameworks: [],
        nodeVersion: null,
        npmVersion: null,
        gitInitialized: false
      }
    };
    
    this.setupSteps = [
      { name: '环境检测和分析', status: 'pending' },
      { name: '安装基础依赖', status: 'pending' },
      { name: '选择项目架构类型', status: 'pending' },
      { name: '选择前端开发语言和框架', status: 'pending' },
      { name: '选择后端开发语言和框架', status: 'pending' },
      { name: '选择UI组件库和工具', status: 'pending' },
      { name: '选择数据库和ORM', status: 'pending' },
      { name: '智能安装缺失依赖', status: 'pending' },
      { name: '配置后端前缀名称', status: 'pending' },
      { name: '配置项目规则文件', status: 'pending' },
      { name: '系统自检', status: 'pending' },
      { name: '启动智能体检测工具', status: 'pending' }
    ];
  }

  /**
   * 主启动方法
   */
  async start() {
    console.log(chalk.cyan('🚀 Builder.Alyr.Net 一键启动脚本 V4.2.3'));
    console.log(chalk.cyan('=================================================='));
    console.log(chalk.gray('版权所有：© 2020-2025 ALYR.NET\n'));
    
    try {
      await this.showWelcome();
      await this.step0_EnvironmentDetection();
      await this.step1_InstallBaseDependencies();
      await this.step2_SelectProjectArchitecture();
      await this.step3_SelectFrontendStack();
      await this.step4_SelectBackendStack();
      await this.step5_SelectUIComponents();
      await this.step6_SelectDatabase();
      await this.step7_SmartInstallDependencies();
      await this.step8_ConfigureBackendPrefix();
      await this.step9_ConfigureProjectRules();
      await this.step10_SystemSelfCheck();
      await this.step11_StartAgent();
      await this.showCompletion();
    } catch (error) {
      console.log(chalk.red(`❌ 安装过程中出现错误: ${error.message}`));
      process.exit(1);
    } finally {
      this.rl.close();
    }
  }

  /**
   * 显示欢迎信息
   */
  async showWelcome() {
    console.log(chalk.yellow('📋 即将执行以下步骤:'));
    this.setupSteps.forEach((step, index) => {
      console.log(chalk.gray(`  ${index + 1}. ${step.name}`));
    });
    console.log('');
    
    const choices = [
      { name: '✅ 开始安装', value: 'start' },
      { name: '📖 查看详细说明', value: 'details' },
      { name: '❌ 退出安装', value: 'exit' }
    ];

    const answer = await inquirer.prompt([{
      type: 'list',
      name: 'action',
      message: '请选择操作:',
      choices: choices
    }]);

    switch (answer.action) {
      case 'start':
        console.log(chalk.green('🚀 开始安装...'));
        break;
      case 'details':
        await this.showDetailedInfo();
        await this.showWelcome(); // 显示详情后返回主菜单
        break;
      case 'exit':
        console.log(chalk.yellow('👋 安装已取消'));
        process.exit(0);
        break;
    }
  }

  /**
   * 显示详细信息
   */
  async showDetailedInfo() {
    console.log(chalk.cyan('\n📖 详细安装说明:'));
    console.log(chalk.white('=================================================='));
    
    console.log(chalk.yellow('\n🎯 安装目标:'));
    console.log(chalk.gray('  • 自动检测并配置项目环境'));
    console.log(chalk.gray('  • 智能选择技术栈组合'));
    console.log(chalk.gray('  • 安装必要的依赖包'));
    console.log(chalk.gray('  • 配置代码规范和项目结构'));
    console.log(chalk.gray('  • 启动智能体检测工具'));
    
    console.log(chalk.yellow('\n⏱️ 预计时间:'));
    console.log(chalk.gray('  • 环境检测: 1-2分钟'));
    console.log(chalk.gray('  • 依赖安装: 3-5分钟'));
    console.log(chalk.gray('  • 配置设置: 2-3分钟'));
    console.log(chalk.gray('  • 总计: 6-10分钟'));
    
    console.log(chalk.yellow('\n🔧 支持的技术栈:'));
    console.log(chalk.gray('  • 前端: React, Vue, Angular, Svelte, Next.js, Nuxt.js'));
    console.log(chalk.gray('  • 后端: Node.js, Express, Nest.js, Koa, Fastify'));
    console.log(chalk.gray('  • 数据库: MySQL, PostgreSQL, MongoDB, SQLite'));
    console.log(chalk.gray('  • UI库: Ant Design, Material-UI, Element Plus, Vuetify'));
    
    console.log(chalk.yellow('\n💡 注意事项:'));
    console.log(chalk.gray('  • 安装过程中可以随时返回上一步'));
    console.log(chalk.gray('  • 如果没有喜欢的选项，可以选择"返回上一步"'));
    console.log(chalk.gray('  • 建议在稳定的网络环境下进行安装'));
    console.log(chalk.gray('  • 安装完成后会自动生成配置文件'));
    
    console.log(chalk.white('\n=================================================='));
    
    const continueChoice = await inquirer.prompt([{
      type: 'confirm',
      name: 'continue',
      message: '是否返回主菜单？',
      default: true
    }]);
    
    if (!continueChoice.continue) {
      process.exit(0);
    }
  }

  /**
   * 步骤0: 环境检测和分析
   */
  async step0_EnvironmentDetection() {
    console.log(chalk.blue('\n🔍 步骤 0: 环境检测和分析'));
    console.log(chalk.gray('正在分析当前项目环境...'));

    try {
      // 检测 Node.js 和 npm 版本
      const nodeVersion = await this.executeCommand('node --version');
      const npmVersion = await this.executeCommand('npm --version');
      
      this.projectConfig.detectedEnvironment.nodeVersion = nodeVersion.trim();
      this.projectConfig.detectedEnvironment.npmVersion = npmVersion.trim();
      
      console.log(chalk.green(`✅ Node.js: ${this.projectConfig.detectedEnvironment.nodeVersion}`));
      console.log(chalk.green(`✅ npm: ${this.projectConfig.detectedEnvironment.npmVersion}`));

      // 检测 package.json
      if (fs.existsSync('./package.json')) {
        this.projectConfig.detectedEnvironment.hasPackageJson = true;
        const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
        
        // 分析现有依赖
        const allDeps = {
          ...packageJson.dependencies || {},
          ...packageJson.devDependencies || {}
        };
        
        this.projectConfig.detectedEnvironment.existingDependencies = Object.keys(allDeps);
        
        // 智能检测框架
        const detectedFrameworks = this.detectFrameworks(allDeps);
        this.projectConfig.detectedEnvironment.detectedFrameworks = detectedFrameworks;
        
        console.log(chalk.green(`✅ 发现 package.json，已安装 ${Object.keys(allDeps).length} 个依赖`));
        
        if (detectedFrameworks.length > 0) {
          console.log(chalk.cyan(`🎯 检测到框架: ${detectedFrameworks.join(', ')}`));
          
          // 自动分析项目架构
          const detectedArchitecture = this.detectProjectArchitecture(detectedFrameworks, allDeps);
          if (detectedArchitecture) {
            console.log(chalk.magenta(`🏗️ 检测到项目架构: ${detectedArchitecture}`));
            this.projectConfig.architecture = detectedArchitecture;
          }
          
          // 询问配置模式
          const choices = [
            { name: '🚀 使用检测到的配置（推荐）', value: 'auto' },
            { name: '🔧 手动选择配置', value: 'manual' },
            { name: '⏭️ 跳过配置，使用默认设置', value: 'skip' }
          ];

          const configChoice = await inquirer.prompt([{
            type: 'list',
            name: 'configMode',
            message: '如何处理项目配置？',
            choices: choices
          }]);
          
          if (configChoice.configMode === 'auto') {
            console.log(chalk.green('🚀 正在应用自动检测的配置...'));
            this.applyDetectedConfiguration(detectedFrameworks, allDeps);
            this.projectConfig.autoConfigured = true;
            
            // 显示自动配置摘要
            this.showAutoConfigSummary();
          } else if (configChoice.configMode === 'skip') {
            console.log(chalk.yellow('⏭️ 跳过配置，将使用默认设置'));
            this.projectConfig.skipConfiguration = true;
          }
        }
      } else {
        console.log(chalk.yellow('⚠️  未发现 package.json，将创建新项目'));
        
        // 新项目选择
        const newProjectChoice = await inquirer.prompt([{
          type: 'list',
          name: 'action',
          message: '检测到这是一个新项目，您希望：',
          choices: [
            { name: '🆕 创建新项目配置', value: 'create' },
            { name: '📋 使用快速模板', value: 'template' },
            { name: '⏭️ 跳过，稍后手动配置', value: 'skip' }
          ]
        }]);
        
        if (newProjectChoice.action === 'template') {
          await this.showQuickTemplates();
        } else if (newProjectChoice.action === 'skip') {
          this.projectConfig.skipConfiguration = true;
          console.log(chalk.yellow('⏭️ 跳过配置，稍后可手动运行配置'));
        }
      }

      // 检测 Git 仓库
      if (fs.existsSync('./.git')) {
        this.projectConfig.detectedEnvironment.gitInitialized = true;
        console.log(chalk.green('✅ Git 仓库已初始化'));
      } else {
        console.log(chalk.yellow('⚠️  Git 仓库未初始化'));
      }

      // 检测项目结构
      const projectStructure = this.analyzeProjectStructure();
      console.log(chalk.cyan(`📁 项目结构分析: ${projectStructure.type}`));
      
      if (projectStructure.suggestions.length > 0) {
        console.log(chalk.gray('💡 建议优化:'));
        projectStructure.suggestions.forEach(suggestion => {
          console.log(chalk.gray(`   - ${suggestion}`));
        });
      }

      this.updateStepStatus(0, 'completed');
    } catch (error) {
      console.log(chalk.red('❌ 环境检测失败:'), error.message);
      this.updateStepStatus(0, 'failed');
    }
  }

  /**
   * 执行命令
   */
  async executeCommand(command) {
    return new Promise((resolve, reject) => {
      try {
        const result = execSync(command, { encoding: 'utf8', stdio: 'pipe' });
        resolve(result);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 步骤1: 安装基础依赖
   */
  async step1_InstallBaseDependencies() {
    this.updateStepStatus(1, 'running');
    console.log(chalk.blue('\n📦 步骤 1: 安装基础依赖'));
    
    try {
      // 检查是否存在package.json
      if (!fs.existsSync('./package.json')) {
        console.log(chalk.yellow('正在初始化package.json...'));
        await this.executeCommand('npm init -y');
      }
      
      // 安装基础依赖
      const baseDependencies = ['chalk', 'inquirer'];
      const baseDevDependencies = ['nodemon'];
      
      if (baseDependencies.length > 0) {
        console.log(chalk.gray(`正在安装基础依赖: ${baseDependencies.join(', ')}`));
        await this.executeCommand(`npm install ${baseDependencies.join(' ')}`);
      }
      
      if (baseDevDependencies.length > 0) {
        console.log(chalk.gray(`正在安装开发依赖: ${baseDevDependencies.join(', ')}`));
        await this.executeCommand(`npm install --save-dev ${baseDevDependencies.join(' ')}`);
      }
      
      this.updateStepStatus(1, 'completed');
    } catch (error) {
      console.log(chalk.red('❌ 基础依赖安装失败:'), error.message);
      this.updateStepStatus(1, 'failed');
      throw error;
    }
  }

  /**
   * 步骤2: 选择项目架构类型
   */
  /**
   * 获取前端选项
   */
  getFrontendOptions() {
    const architecture = this.projectConfig.architecture;
    
    if (architecture === 'mobile') {
      return [
        { name: 'React Native', framework: 'React Native', packages: ['react-native'] },
        { name: 'Flutter', framework: 'Flutter', packages: [] },
        { name: 'Ionic', framework: 'Ionic', packages: ['@ionic/react'] },
        { name: 'Xamarin', framework: 'Xamarin', packages: [] }
      ];
    } else if (architecture === 'desktop') {
      return [
        { name: 'Electron + React', framework: 'Electron + React', packages: ['electron', 'react'] },
        { name: 'Electron + Vue', framework: 'Electron + Vue', packages: ['electron', 'vue'] },
        { name: 'Tauri + React', framework: 'Tauri + React', packages: ['react'] },
        { name: 'Qt', framework: 'Qt', packages: [] }
      ];
    } else {
      return [
        { name: 'React', framework: 'React', packages: ['react', 'react-dom'] },
        { name: 'Vue 3', framework: 'Vue 3', packages: ['vue'] },
        { name: 'Angular', framework: 'Angular', packages: ['@angular/core'] },
        { name: 'Next.js', framework: 'Next.js', packages: ['next', 'react'] },
        { name: 'Nuxt.js', framework: 'Nuxt.js', packages: ['nuxt'] },
        { name: 'Svelte', framework: 'Svelte', packages: ['svelte'] },
        { name: 'Vanilla JS', framework: 'Vanilla JS', packages: [] }
      ];
    }
  }

  /**
   * 步骤7: 智能安装缺失依赖
   */
  async step7_SmartInstallDependencies() {
    this.updateStepStatus(7, 'running');
    console.log(chalk.blue('\n📦 步骤 7: 智能安装缺失依赖'));
    
    try {
      // 设置框架依赖
      this.setFrameworkDependencies();
      
      // 检查现有依赖
      let existingDeps = [];
      if (fs.existsSync('./package.json')) {
        const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
        existingDeps = [
          ...Object.keys(packageJson.dependencies || {}),
          ...Object.keys(packageJson.devDependencies || {})
        ];
      }
      
      // 过滤出需要安装的依赖
      const newProdDeps = this.projectConfig.dependencies.production?.filter(dep => !existingDeps.includes(dep)) || [];
      const newDevDeps = this.projectConfig.dependencies.development?.filter(dep => !existingDeps.includes(dep)) || [];
      
      if (newProdDeps.length === 0 && newDevDeps.length === 0) {
        console.log(chalk.green('✅ 所有依赖都已安装'));
        this.updateStepStatus(7, 'completed');
        return;
      }
      
      // 显示将要安装的依赖
      if (newProdDeps.length > 0) {
        console.log(chalk.cyan(`📦 生产依赖: ${newProdDeps.join(', ')}`));
      }
      if (newDevDeps.length > 0) {
        console.log(chalk.cyan(`🔧 开发依赖: ${newDevDeps.join(', ')}`));
      }
      
      // 询问用户确认
      const confirm = await inquirer.prompt([{
        type: 'confirm',
        name: 'install',
        message: '是否安装这些依赖？',
        default: true
      }]);
      
      if (!confirm.install) {
        console.log(chalk.yellow('⏭️  跳过依赖安装'));
        this.updateStepStatus(7, 'completed');
        return;
      }
      
      // 安装生产依赖
      if (newProdDeps.length > 0) {
        console.log(chalk.gray('正在安装生产依赖...'));
        const prodCommand = `npm install ${newProdDeps.join(' ')}`;
        await this.executeCommand(prodCommand);
      }
      
      // 安装开发依赖
      if (newDevDeps.length > 0) {
        console.log(chalk.gray('正在安装开发依赖...'));
        const devCommand = `npm install --save-dev ${newDevDeps.join(' ')}`;
        await this.executeCommand(devCommand);
      }
      
      console.log(chalk.green('✅ 依赖安装完成'));
      this.updateStepStatus(7, 'completed');
    } catch (error) {
      console.log(chalk.red('❌ 依赖安装失败:'), error.message);
      this.updateStepStatus(7, 'failed');
      throw error;
    }
  }

  /**
   * 步骤8: 配置后端前缀名称
   */
  async step8_ConfigureBackendPrefix() {
    this.updateStepStatus(8, 'running');
    console.log(chalk.blue('\n🏷️ 步骤8: 配置后端强制前缀名称...'));
    
    console.log(chalk.yellow('后端文件命名规范说明:'));
    console.log(chalk.gray('  - 控制器: {prefix}-{module}.controller.ts'));
    console.log(chalk.gray('  - 服务类: {prefix}-{module}.service.ts'));
    console.log(chalk.gray('  - 实体类: {prefix}-{module}.entity.ts'));
    console.log(chalk.gray('  - 示例: Alyr-user.controller.ts'));
    
    try {
      const answer = await inquirer.prompt([{
        type: 'input',
        name: 'prefix',
        message: '请输入后端文件前缀名称 (直接回车使用默认 Alyr):',
        default: 'Alyr',
        validate: (input) => {
          if (input && !/^[a-zA-Z][a-zA-Z0-9-_]*$/.test(input)) {
            return '前缀名称只能包含字母、数字、连字符和下划线，且必须以字母开头';
          }
          return true;
        }
      }]);
      
      // 如果用户没有输入，使用默认前缀 Alyr
      const prefix = answer.prefix || 'Alyr';
      this.projectConfig.backendPrefix = prefix;
      
      console.log(chalk.yellow(`使用前缀: ${prefix}`));
      
      // 强制同步所有后端文件 - 无需确认
      console.log(chalk.yellow('\n🔍 正在强制同步所有后端文件前缀...'));
      console.log(chalk.red('⚠️  注意：将强制更新所有后端文件前缀，无论当前前缀是什么！'));
      await this.forceUpdateAllBackendFiles(this.projectConfig.backendPrefix);
      
      // 更新配置文件和关联引用
      await this.updateConfigFiles();
      await this.updateFileReferences(this.projectConfig.backendPrefix);
      
      console.log(chalk.green(`✅ 后端前缀已强制同步为: ${this.projectConfig.backendPrefix}`));
      this.updateStepStatus(8, 'completed');
    } catch (error) {
      console.log(chalk.red('❌ 后端前缀配置失败:'), error.message);
      this.updateStepStatus(8, 'failed');
      throw error;
    }
  }

  /**
   * 步骤9: 配置项目规则文件
   */
  async step9_ConfigureProjectRules() {
    this.updateStepStatus(9, 'running');
    console.log(chalk.blue('\n📋 步骤 9: 配置项目规则文件'));
    
    try {
      const rulesPath = './project_rules.md';
      
      if (fs.existsSync(rulesPath)) {
        const overwrite = await inquirer.prompt([{
          type: 'confirm',
          name: 'overwrite',
          message: 'project_rules.md 已存在，是否覆盖？',
          default: false
        }]);
        
        if (!overwrite.overwrite) {
          console.log(chalk.yellow('⏭️  跳过规则文件创建'));
          this.updateStepStatus(9, 'completed');
          return;
        }
      }
      
      await this.createProjectRulesFile(rulesPath);
      await this.updateConfigFiles();
      
      this.updateStepStatus(9, 'completed');
    } catch (error) {
      console.log(chalk.red('❌ 项目规则配置失败:'), error.message);
      this.updateStepStatus(9, 'failed');
      throw error;
    }
  }

  /**
   * 步骤10: 系统自检
   */
  async step10_SystemSelfCheck() {
    this.updateStepStatus(10, 'running');
    console.log(chalk.blue('\n🔍 步骤 10: 系统自检'));
    
    try {
      console.log(chalk.gray('正在检查配置文件...'));
      this.checkConfigFiles();
      
      console.log(chalk.gray('正在检查核心模块...'));
      this.checkCoreModules();
      
      console.log(chalk.gray('正在检查权限设置...'));
      this.checkPermissions();
      
      console.log(chalk.green('✅ 系统自检通过'));
      this.updateStepStatus(10, 'completed');
    } catch (error) {
      console.log(chalk.red('❌ 系统自检失败:'), error.message);
      this.updateStepStatus(10, 'failed');
      throw error;
    }
  }

  /**
   * 步骤11: 启动智能体检测工具
   */
  async step11_StartAgent() {
    this.updateStepStatus(11, 'running');
    console.log(chalk.blue('\n🤖 步骤 11: 启动智能体检测工具'));
    
    try {
      const startAgent = await inquirer.prompt([{
        type: 'confirm',
        name: 'start',
        message: '是否启动智能体检测工具？',
        default: true
      }]);
      
      if (startAgent.start) {
        console.log(chalk.gray('正在启动智能体检测工具...'));
        // 这里可以启动智能体检测工具
        console.log(chalk.green('✅ 智能体检测工具已启动'));
      } else {
        console.log(chalk.yellow('⏭️  跳过智能体检测工具启动'));
      }
      
      this.updateStepStatus(11, 'completed');
    } catch (error) {
      console.log(chalk.red('❌ 智能体检测工具启动失败:'), error.message);
      this.updateStepStatus(11, 'failed');
      throw error;
    }
  }

  /**
   * 显示完成信息
   */
  async showCompletion() {
    console.log(chalk.green('\n🎉 一键安装完成！'));
    console.log(chalk.cyan('=================================================='));
    
    // 显示配置摘要 - 添加安全检查
    console.log(chalk.yellow('📋 配置摘要:'));
    if (this.projectConfig.architecture) {
      console.log(chalk.gray(`   架构: ${this.projectConfig.architecture}`));
    }
    if (this.projectConfig.frontendStack?.framework) {
      console.log(chalk.gray(`   前端: ${this.projectConfig.frontendStack.framework}`));
    }
    if (this.projectConfig.backendStack) {
      // 安全处理后端栈信息
      const backendInfo = typeof this.projectConfig.backendStack === 'object' 
        ? this.projectConfig.backendStack.framework || this.projectConfig.backendStack
        : this.projectConfig.backendStack;
      console.log(chalk.gray(`   后端: ${backendInfo}`));
    }
    if (this.projectConfig.backendPrefix) {
      console.log(chalk.gray(`   后端前缀: ${this.projectConfig.backendPrefix}`));
    }
    
    // 执行配置同步和完成流程
    await this.completeSetup();
    
    console.log(chalk.green('\n✨ 项目已准备就绪，开始您的开发之旅吧！'));
  }

  /**
   * 步骤2: 选择项目架构类型
   */
  async step2_SelectProjectArchitecture() {
    this.updateStepStatus(2, 'running');
    console.log(chalk.blue('\n🏗️ 步骤2: 选择项目架构类型...'));
    
    // 如果已经检测到架构，询问是否使用
    if (this.projectConfig.architecture) {
      console.log(chalk.cyan(`🎯 已检测到架构: ${this.projectConfig.architecture}`));
      
      const useDetected = await inquirer.prompt([{
        type: 'confirm',
        name: 'use',
        message: '是否使用检测到的架构类型？',
        default: true
      }]);
      
      if (useDetected.use) {
        console.log(chalk.green(`✅ 使用检测到的架构: ${this.projectConfig.architecture}`));
        this.updateStepStatus(2, 'completed');
        return;
      }
    }
    
    const architectures = [
      { 
        name: '前后端分离 (SPA + API)', 
        value: 'spa-api',
        description: '前端单页应用 + 后端API服务',
        suitable: '适合大型项目、团队协作开发'
      },
      { 
        name: '全栈应用 (SSR)', 
        value: 'fullstack',
        description: '服务端渲染，前后端一体化',
        suitable: '适合SEO要求高、快速开发'
      },
      { 
        name: '微服务架构', 
        value: 'microservice',
        description: '多个独立服务组成',
        suitable: '适合大型企业级应用'
      },
      { 
        name: '静态网站 + 无服务器', 
        value: 'jamstack',
        description: 'JAMStack架构，静态生成',
        suitable: '适合内容网站、博客'
      },
      { 
        name: '桌面应用 (Electron)', 
        value: 'desktop',
        description: '跨平台桌面应用',
        suitable: '适合工具类软件'
      },
      { 
        name: '移动应用 (跨平台)', 
        value: 'mobile',
        description: 'React Native / Flutter',
        suitable: '适合移动端应用'
      }
    ];
    
    // 添加跳过和返回选项
    const choicesWithOptions = this.addSkipOption(
      architectures.map(arch => ({
        name: `${arch.name} - ${arch.description}`,
        value: arch.value,
        short: arch.name
      })), 
      '项目架构'
    );

    const answer = await inquirer.prompt([{
      type: 'list',
      name: 'architecture',
      message: '请选择项目架构类型:',
      choices: choicesWithOptions
    }]);
    
    // 处理跳过和返回选项
    if (answer.architecture === 'SKIP_STEP') {
      this.handleSkipStep('项目架构');
      this.projectConfig.architecture = 'spa-api'; // 默认架构
      this.updateStepStatus(2, 'completed');
      return;
    }
    
    if (answer.architecture === 'RETURN_PREVIOUS') {
      console.log(chalk.yellow('🔙 返回上一步...'));
      await this.step0_EnvironmentDetection();
      return;
    }
    
    const selectedArch = architectures.find(arch => arch.value === answer.architecture);
    this.projectConfig.architecture = selectedArch.name;
    console.log(chalk.green(`✅ 已选择: ${selectedArch.name}`));
    this.updateStepStatus(2, 'completed');
  }

  /**
   * 步骤3: 选择前端开发语言和框架
   */
  async step3_SelectFrontendStack() {
    this.updateStepStatus(3, 'running');
    console.log(chalk.blue('\n🎨 步骤3: 选择前端开发语言和框架...'));
    
    // 如果已经检测到前端栈，询问是否使用
    if (this.projectConfig.frontendStack) {
      console.log(chalk.cyan(`🎯 已检测到前端栈: ${this.projectConfig.frontendStack.framework} (${this.projectConfig.frontendStack.language})`));
      
      const useDetected = await inquirer.prompt([{
        type: 'confirm',
        name: 'use',
        message: '是否使用检测到的前端技术栈？',
        default: true
      }]);
      
      if (useDetected.use) {
        console.log(chalk.green(`✅ 使用检测到的前端栈: ${this.projectConfig.frontendStack.framework}`));
        this.updateStepStatus(3, 'completed');
        return;
      }
    }
    
    // 根据架构类型提供不同的前端选项
    let frontendOptions = [];
    
    if (this.projectConfig.architecture.includes('SPA') || 
        this.projectConfig.architecture.includes('全栈')) {
      frontendOptions = [
        {
          name: 'React + TypeScript',
          value: 'react-ts',
          language: 'TypeScript',
          framework: 'React',
          buildTool: 'Vite',
          features: ['JSX', 'Hooks', 'Context API', 'React Router']
        },
        {
          name: 'Vue 3 + TypeScript',
          value: 'vue3-ts',
          language: 'TypeScript',
          framework: 'Vue 3',
          buildTool: 'Vite',
          features: ['Composition API', 'Vue Router', 'Pinia']
        },
        {
          name: 'Angular + TypeScript',
          value: 'angular-ts',
          language: 'TypeScript',
          framework: 'Angular',
          buildTool: 'Angular CLI',
          features: ['依赖注入', 'RxJS', 'Angular Router']
        },
        {
          name: 'Svelte + TypeScript',
          value: 'svelte-ts',
          language: 'TypeScript',
          framework: 'Svelte',
          buildTool: 'SvelteKit',
          features: ['编译时优化', '无虚拟DOM', '小体积']
        },
        {
          name: 'Next.js (React SSR)',
          value: 'nextjs',
          language: 'TypeScript',
          framework: 'Next.js',
          buildTool: 'Next.js',
          features: ['SSR', 'SSG', 'API Routes', 'Image优化']
        },
        {
          name: 'Nuxt.js (Vue SSR)',
          value: 'nuxtjs',
          language: 'TypeScript',
          framework: 'Nuxt.js',
          buildTool: 'Nuxt.js',
          features: ['SSR', 'SSG', '自动路由', '模块系统']
        }
      ];
    } else if (this.projectConfig.architecture.includes('移动')) {
      frontendOptions = [
        {
          name: 'React Native + TypeScript',
          value: 'react-native',
          language: 'TypeScript',
          framework: 'React Native',
          buildTool: 'Metro',
          features: ['原生性能', '热重载', '跨平台']
        },
        {
          name: 'uni-app + Vue',
          value: 'uniapp',
          language: 'JavaScript',
          framework: 'uni-app',
          buildTool: 'HBuilderX',
          features: ['多端发布', 'Vue语法', '原生插件']
        },
        {
          name: 'Taro + React',
          value: 'taro',
          language: 'TypeScript',
          framework: 'Taro',
          buildTool: 'Taro CLI',
          features: ['多端统一', 'React语法', '京东开源']
        }
      ];
    } else if (this.projectConfig.architecture.includes('桌面')) {
      frontendOptions = [
        {
          name: 'Electron + React',
          value: 'electron-react',
          language: 'TypeScript',
          framework: 'Electron + React',
          buildTool: 'Electron Builder',
          features: ['跨平台', '原生API', 'Web技术']
        },
        {
          name: 'Tauri + React',
          value: 'tauri-react',
          language: 'TypeScript',
          framework: 'Tauri + React',
          buildTool: 'Tauri CLI',
          features: ['Rust后端', '小体积', '高性能']
        }
      ];
    }
    
    // 添加跳过和返回选项
    const choicesWithOptions = this.addSkipOption(
      frontendOptions.map(option => ({
        name: `${option.name} - ${option.features.join(', ')}`,
        value: option.value,
        short: option.name
      })),
      '前端技术栈'
    );

    const answer = await inquirer.prompt([{
      type: 'list',
      name: 'frontend',
      message: '请选择前端技术栈:',
      choices: choicesWithOptions
    }]);

    // 处理跳过和返回选项
    if (answer.frontend === 'SKIP_STEP') {
      this.handleSkipStep('前端技术栈');
      this.updateStepStatus(3, 'completed');
      return;
    }
    
    if (answer.frontend === 'RETURN_PREVIOUS') {
      console.log(chalk.yellow('🔙 返回上一步...'));
      await this.step2_SelectProjectArchitecture();
      return;
    }
    
    const selectedFrontend = frontendOptions.find(option => option.value === answer.frontend);
    this.projectConfig.frontendStack = {
      language: selectedFrontend.language,
      framework: selectedFrontend.framework
    };
    console.log(chalk.green(`✅ 已选择: ${selectedFrontend.name}`));
    this.updateStepStatus(3, 'completed');
  }

  /**
   * 步骤4: 选择后端开发语言和框架
   */
  async step4_SelectBackendStack() {
    this.updateStepStatus(4, 'running');
    console.log(chalk.blue('\n⚙️ 步骤4: 选择后端开发语言和框架...'));
    
  // 如果已经检测到后端栈，询问是否使用
    if (this.projectConfig.backendStack) {
      console.log(chalk.cyan(`🎯 已检测到后端栈: ${this.projectConfig.backendStack.framework} (${this.projectConfig.backendStack.language})`));
      
      const useDetected = await inquirer.prompt([{
        type: 'confirm',
        name: 'use',
        message: '是否使用检测到的后端技术栈？',
        default: true
      }]);
      
      if (useDetected.use) {
        console.log(chalk.green(`✅ 使用检测到的后端栈: ${this.projectConfig.backendStack.framework}`));
        this.updateStepStatus(4, 'completed');
        return;
      }
    }
    
    // 如果是静态网站或纯前端，跳过后端选择
    if (this.projectConfig.architecture.includes('JAMStack')) {
      console.log(chalk.yellow('📝 JAMStack架构，跳过后端配置'));
      this.projectConfig.backendStack = { language: 'None', framework: 'JAMStack' };
      this.updateStepStatus(4, 'completed');
      return;
    }
    
    const backendOptions = [
      {
        name: 'Node.js + Express',
        value: 'node-express',
        language: 'JavaScript/TypeScript',
        framework: 'Express.js',
        features: ['轻量级', '中间件丰富', '快速开发'],
        suitable: '适合API服务、微服务'
      },
      {
        name: 'Node.js + Nest.js',
        value: 'node-nestjs',
        language: 'TypeScript',
        framework: 'Nest.js',
        features: ['装饰器', '依赖注入', '模块化'],
        suitable: '适合企业级应用、大型项目'
      },
      {
        name: 'Node.js + Koa',
        value: 'node-koa',
        language: 'JavaScript/TypeScript',
        framework: 'Koa.js',
        features: ['async/await', '洋葱模型', '轻量级'],
        suitable: '适合现代化API开发'
      },
      {
        name: 'Java + Spring Boot',
        value: 'java-spring',
        language: 'Java',
        framework: 'Spring Boot',
        features: ['自动配置', '微服务', '企业级'],
        suitable: '适合大型企业应用'
      },
      {
        name: 'Python + Django',
        value: 'python-django',
        language: 'Python',
        framework: 'Django',
        features: ['ORM', '管理后台', '全功能'],
        suitable: '适合内容管理、快速开发'
      },
      {
        name: 'Python + FastAPI',
        value: 'python-fastapi',
        language: 'Python',
        framework: 'FastAPI',
        features: ['异步', '自动文档', '类型提示'],
        suitable: '适合API服务、机器学习'
      },
      {
        name: 'Go + Gin',
        value: 'go-gin',
        language: 'Go',
        framework: 'Gin',
        features: ['高性能', '并发', '编译型'],
        suitable: '适合高并发服务'
      },
      {
        name: 'C# + .NET Core',
        value: 'csharp-dotnet',
        language: 'C#',
        framework: '.NET Core',
        features: ['跨平台', '高性能', '企业级'],
        suitable: '适合企业应用、微服务'
      },
      {
        name: 'PHP + Laravel',
        value: 'php-laravel',
        language: 'PHP',
        framework: 'Laravel',
        features: ['Eloquent ORM', '路由', '中间件'],
        suitable: '适合Web应用、快速开发'
      },
      {
        name: 'Ruby + Rails',
        value: 'ruby-rails',
        language: 'Ruby',
        framework: 'Ruby on Rails',
        features: ['约定优于配置', 'ActiveRecord', 'RESTful'],
        suitable: '适合快速原型、创业项目'
      }
    ];
    
    // 添加跳过和返回选项
    const choicesWithOptions = this.addSkipOption(
      backendOptions.map(option => ({
        name: `${option.name} - ${option.features.join(', ')} (${option.suitable})`,
        value: option.value,
        short: option.name
      })),
      '后端技术栈'
    );

    const answer = await inquirer.prompt([{
      type: 'list',
      name: 'backend',
      message: '请选择后端技术栈:',
      choices: choicesWithOptions
    }]);

    // 处理跳过和返回选项
    if (answer.backend === 'SKIP_STEP') {
      this.handleSkipStep('后端技术栈');
      this.updateStepStatus(4, 'completed');
      return;
    }
    
    if (answer.backend === 'RETURN_PREVIOUS') {
      console.log(chalk.yellow('🔙 返回上一步...'));
      await this.step3_SelectFrontendStack();
      return;
    }
    
    const selectedBackend = backendOptions.find(option => option.value === answer.backend);
    this.projectConfig.backendStack = {
      language: selectedBackend.language,
      framework: selectedBackend.framework
    };
    console.log(chalk.green(`✅ 已选择: ${selectedBackend.name}`));
    this.updateStepStatus(4, 'completed');
  }

  /**
   * 步骤5: 选择UI组件库和工具
   */
  async step5_SelectUIComponents() {
    this.updateStepStatus(5, 'running');
    console.log(chalk.blue('\n🎨 步骤5: 选择UI组件库和工具...'));
    
    // 如果已经检测到UI组件库，询问是否使用
    if (this.projectConfig.uiComponents) {
      console.log(chalk.cyan(`🎯 已检测到UI组件库: ${this.projectConfig.uiComponents.name}`));
      
      const useDetected = await inquirer.prompt([{
        type: 'confirm',
        name: 'use',
        message: '是否使用检测到的UI组件库？',
        default: true
      }]);
      
      if (useDetected.use) {
        console.log(chalk.green(`✅ 使用检测到的UI组件库: ${this.projectConfig.uiComponents.name}`));
        this.updateStepStatus(5, 'completed');
        return;
      }
    }
    
    if (this.projectConfig.architecture.includes('JAMStack') || 
        this.projectConfig.architecture.includes('Backend API Only')) {
      console.log(chalk.yellow('当前架构不需要UI组件库，跳过此步骤'));
      this.updateStepStatus(5, 'completed');
      return;
    }
    
    const uiOptions = this.getUIComponentOptions();
    
    // 添加跳过和返回选项
    const choicesWithOptions = this.addSkipOption(
      uiOptions.map(option => ({
        name: `${option.name} - ${option.description}`,
        value: option.value,
        short: option.name
      })),
      'UI组件库'
    );

    const answer = await inquirer.prompt([{
      type: 'list',
      name: 'ui',
      message: '请选择UI组件库:',
      choices: choicesWithOptions
    }]);

    // 处理跳过和返回选项
    if (answer.ui === 'SKIP_STEP') {
      this.handleSkipStep('UI组件库');
      this.updateStepStatus(5, 'completed');
      return;
    }
    
    if (answer.ui === 'RETURN_PREVIOUS') {
      console.log(chalk.yellow('🔙 返回上一步...'));
      await this.step4_SelectBackendStack();
      return;
    }
    
    const selectedUI = uiOptions.find(option => option.value === answer.ui);
    this.projectConfig.uiComponents = selectedUI;
    console.log(chalk.green(`✅ 已选择UI组件库: ${selectedUI.name}`));
    
    this.updateStepStatus(5, 'completed');
  }

  /**
   * 步骤6: 选择数据库和ORM
   */
  async step6_SelectDatabase() {
    this.updateStepStatus(6, 'running');
    console.log(chalk.blue('\n🗄️ 步骤6: 选择数据库和ORM...'));
    
    // 如果已经检测到数据库和ORM，询问是否使用
    if (this.projectConfig.database && this.projectConfig.orm) {
      console.log(chalk.cyan(`🎯 已检测到数据库: ${this.projectConfig.database.name}`));
      console.log(chalk.cyan(`🎯 已检测到ORM: ${this.projectConfig.orm.name}`));
      
      const useDetected = await inquirer.prompt([{
        type: 'confirm',
        name: 'use',
        message: '是否使用检测到的数据库和ORM配置？',
        default: true
      }]);
      
      if (useDetected.use) {
        console.log(chalk.green(`✅ 使用检测到的数据库: ${this.projectConfig.database.name}`));
        console.log(chalk.green(`✅ 使用检测到的ORM: ${this.projectConfig.orm.name}`));
        this.updateStepStatus(6, 'completed');
        return;
      }
    }
    
    if (this.projectConfig.architecture.includes('Frontend Only') || 
        this.projectConfig.architecture.includes('JAMStack')) {
      console.log(chalk.yellow('当前架构不需要数据库，跳过此步骤'));
      this.updateStepStatus(6, 'completed');
      return;
    }
    
    const dbOptions = this.getDatabaseOptions();
    
    // 添加跳过和返回选项
    const dbChoicesWithOptions = this.addSkipOption(
      dbOptions.map(option => ({
        name: `${option.name} - ${option.description}`,
        value: option.value,
        short: option.name
      })),
      '数据库'
    );

    const dbAnswer = await inquirer.prompt([{
      type: 'list',
      name: 'database',
      message: '请选择数据库类型:',
      choices: dbChoicesWithOptions
    }]);

    // 处理跳过和返回选项
    if (dbAnswer.database === 'SKIP_STEP') {
      this.handleSkipStep('数据库');
      this.updateStepStatus(6, 'completed');
      return;
    }
    
    if (dbAnswer.database === 'RETURN_PREVIOUS') {
      console.log(chalk.yellow('🔙 返回上一步...'));
      await this.step5_SelectUIComponents();
      return;
    }
    
    const selectedDB = dbOptions.find(option => option.value === dbAnswer.database);
    this.projectConfig.database = selectedDB;
    console.log(chalk.green(`✅ 已选择数据库: ${selectedDB.name}`));
    
    // 选择ORM
    const ormOptions = this.getORMOptions(this.projectConfig.backendStack);
    if (ormOptions.length > 0) {
      // 添加返回选项
      const ormChoicesWithReturn = [
        ...ormOptions.map(option => ({
          name: `${option.name} - ${option.description}`,
          value: option.value,
          short: option.name
        })),
        new inquirer.Separator(),
        { name: '🔙 重新选择数据库', value: 'RETURN_DATABASE' }
      ];

      const ormAnswer = await inquirer.prompt([{
        type: 'list',
        name: 'orm',
        message: '请选择ORM/ODM:',
        choices: ormChoicesWithReturn
      }]);

      // 处理返回选项
      if (ormAnswer.orm === 'RETURN_DATABASE') {
        console.log(chalk.yellow('🔙 重新选择数据库...'));
        // 重新开始数据库选择流程
        const dbOptions = this.getDatabaseOptions();
        
        // 添加返回选项
        const dbChoicesWithReturn = [
          ...dbOptions.map(option => ({
            name: `${option.name} - ${option.description}`,
            value: option.value,
            short: option.name
          })),
          new inquirer.Separator(),
          { name: '🔙 返回上一步', value: 'RETURN_PREVIOUS' }
        ];

        const dbAnswer = await inquirer.prompt([{
          type: 'list',
          name: 'database',
          message: '请选择数据库类型:',
          choices: dbChoicesWithReturn
        }]);

        // 处理返回选项
        if (dbAnswer.database === 'RETURN_PREVIOUS') {
          console.log(chalk.yellow('🔙 返回上一步...'));
          await this.step5_SelectUIComponents();
          return;
        }

        const selectedDB = dbOptions.find(option => option.value === dbAnswer.database);
        this.projectConfig.database = selectedDB;
        console.log(chalk.green(`✅ 已选择数据库: ${selectedDB.name}`));

        // 重新选择ORM
        const newOrmOptions = this.getORMOptions(this.projectConfig.backendStack);
        if (newOrmOptions.length > 0) {
          const newOrmAnswer = await inquirer.prompt([{
            type: 'list',
            name: 'orm',
            message: '请选择ORM/ODM:',
            choices: newOrmOptions.map(option => ({
              name: `${option.name} - ${option.description}`,
              value: option.value,
              short: option.name
            }))
          }]);
          
          const selectedORM = newOrmOptions.find(option => option.value === newOrmAnswer.orm);
          this.projectConfig.orm = selectedORM;
          console.log(chalk.green(`✅ 已选择ORM: ${selectedORM.name}`));
        }
        
        this.updateStepStatus(6, 'completed');
        return;
      }
      
      const selectedORM = ormOptions.find(option => option.value === ormAnswer.orm);
      this.projectConfig.orm = selectedORM;
      console.log(chalk.green(`✅ 已选择ORM: ${selectedORM.name}`));
    }
    
    this.updateStepStatus(6, 'completed');
  }

  /**
   * 步骤7: 智能安装缺失依赖
   */
  async step7_SmartInstallDependencies() {
    console.log(chalk.blue('\n📦 步骤 7: 智能安装缺失依赖'));
    
    // 设置框架依赖
    this.setFrameworkDependencies();
    
    const existingDeps = this.projectConfig.detectedEnvironment.existingDependencies || [];
    
    // 过滤出需要安装的依赖
     const newProdDeps = this.projectConfig.dependencies.production.filter(dep => 
       !existingDeps.includes(dep)
     );
     const newDevDeps = this.projectConfig.dependencies.development.filter(dep => 
       !existingDeps.includes(dep)
     );
    
    console.log(chalk.cyan(`📋 依赖分析:`));
    console.log(chalk.gray(`   已存在: ${existingDeps.length} 个依赖`));
    console.log(chalk.gray(`   需安装生产依赖: ${newProdDeps.length} 个`));
    console.log(chalk.gray(`   需安装开发依赖: ${newDevDeps.length} 个`));
    
    if (newProdDeps.length === 0 && newDevDeps.length === 0) {
      console.log(chalk.green('✅ 所有依赖已存在，跳过安装步骤'));
      return;
    }
    
    // 显示将要安装的依赖
    if (newProdDeps.length > 0) {
      console.log(chalk.cyan('\n📦 将安装生产依赖:'));
      newProdDeps.forEach(dep => console.log(chalk.gray(`   - ${dep}`)));
    }
    
    if (newDevDeps.length > 0) {
      console.log(chalk.cyan('\n🔧 将安装开发依赖:'));
      newDevDeps.forEach(dep => console.log(chalk.gray(`   - ${dep}`)));
    }
    
    // 询问用户确认
     const confirmInstall = await inquirer.prompt([{
       type: 'confirm',
       name: 'install',
       message: '是否继续安装这些依赖？',
       default: true
     }]);
     
     if (!confirmInstall.install) {
       console.log(chalk.yellow('⚠️  跳过依赖安装'));
       return;
     }
    
    try {
      // 安装生产依赖
       if (newProdDeps.length > 0) {
         console.log(chalk.blue('\n📦 安装生产依赖...'));
         const prodCommand = `npm install ${newProdDeps.join(' ')}`;
         console.log(chalk.gray(`执行: ${prodCommand}`));
         await this.executeCommand(prodCommand);
         console.log(chalk.green('✅ 生产依赖安装完成'));
       }
       
       // 安装开发依赖
       if (newDevDeps.length > 0) {
         console.log(chalk.blue('\n🔧 安装开发依赖...'));
         const devCommand = `npm install --save-dev ${newDevDeps.join(' ')}`;
         console.log(chalk.gray(`执行: ${devCommand}`));
         await this.executeCommand(devCommand);
         console.log(chalk.green('✅ 开发依赖安装完成'));
       }
      
      console.log(chalk.green('\n🎉 所有依赖安装完成！'));
      
    } catch (error) {
      console.error(chalk.red('❌ 依赖安装失败:'), error.message);
      
      // 提供手动安装命令
      console.log(chalk.yellow('\n📝 您可以手动执行以下命令:'));
      if (newProdDeps.length > 0) {
        console.log(chalk.gray(`npm install ${newProdDeps.join(' ')}`));
      }
      if (newDevDeps.length > 0) {
        console.log(chalk.gray(`npm install --save-dev ${newDevDeps.join(' ')}`));
      }
    }
  }

  /**
   * 强制更新所有后端文件前缀 - 无需确认，完全同步
   */
  async forceUpdateAllBackendFiles(newPrefix) {
    const backendDirs = ['server', 'backend', 'core', 'utils', 'config'];
    const backendExtensions = ['.controller.ts', '.controller.js', '.service.ts', '.service.js', 
                              '.module.ts', '.module.js', '.entity.ts', '.entity.js', 
                              '.dto.ts', '.dto.js', '.guard.ts', '.guard.js',
                              '.middleware.ts', '.middleware.js', '.interceptor.ts', '.interceptor.js',
                              '.resolver.ts', '.resolver.js', '.repository.ts', '.repository.js'];
    
    let totalScanned = 0;
    let totalRenamed = 0;
    const renamedFiles = [];
    const errors = [];
    
    console.log(chalk.blue('\n🔄 开始强制同步后端文件前缀...'));
    
    for (const dir of backendDirs) {
      const dirPath = path.join(process.cwd(), dir);
      if (fs.existsSync(dirPath)) {
        console.log(chalk.gray(`  📁 扫描目录: ${dir}/`));
        const files = await this.scanDirectoryRecursively(dirPath);
        
        for (const filePath of files) {
          const fileName = path.basename(filePath);
          const fileExt = backendExtensions.find(ext => fileName.endsWith(ext));
          
          if (fileExt) {
            totalScanned++;
            
            // 强制更新前缀，无论当前前缀是什么
            let newFileName;
            
            // 检查是否已经有正确的前缀
            if (fileName.startsWith(`${newPrefix}-`)) {
              console.log(chalk.gray(`    ✓ 已正确: ${fileName}`));
              continue;
            }
            
            // 移除任何现有前缀并添加新前缀
            const existingPrefixMatch = fileName.match(/^([A-Za-z0-9]+)-(.+)$/);
            if (existingPrefixMatch) {
              // 有现有前缀，替换为新前缀
              newFileName = `${newPrefix}-${existingPrefixMatch[2]}`;
              console.log(chalk.yellow(`    🔄 替换前缀: ${existingPrefixMatch[1]}- → ${newPrefix}-`));
            } else {
              // 没有前缀，直接添加新前缀
              newFileName = `${newPrefix}-${fileName}`;
              console.log(chalk.blue(`    ➕ 添加前缀: ${fileName} → ${newFileName}`));
            }
            
            const newFilePath = path.join(path.dirname(filePath), newFileName);
            
            try {
              // 检查目标文件是否已存在
              if (fs.existsSync(newFilePath) && newFilePath !== filePath) {
                console.log(chalk.red(`    ⚠️  目标文件已存在，跳过: ${newFileName}`));
                continue;
              }
              
              fs.renameSync(filePath, newFilePath);
              renamedFiles.push({
                old: path.relative(process.cwd(), filePath),
                new: path.relative(process.cwd(), newFilePath),
                oldName: fileName,
                newName: newFileName
              });
              totalRenamed++;
              console.log(chalk.green(`    ✅ ${fileName} → ${newFileName}`));
              
            } catch (error) {
              errors.push({ file: fileName, error: error.message });
              console.log(chalk.red(`    ❌ 重命名失败: ${fileName} - ${error.message}`));
            }
          }
        }
      } else {
        console.log(chalk.gray(`  📁 目录不存在，跳过: ${dir}/`));
      }
    }
    
    // 输出统计结果
    console.log(chalk.blue('\n📊 同步统计结果:'));
    console.log(chalk.gray(`  📄 扫描文件总数: ${totalScanned}`));
    console.log(chalk.green(`  ✅ 成功重命名: ${totalRenamed}`));
    console.log(chalk.red(`  ❌ 失败数量: ${errors.length}`));
    
    if (renamedFiles.length > 0) {
      console.log(chalk.yellow('\n📋 重命名详细清单:'));
      renamedFiles.forEach((file, index) => {
        console.log(chalk.gray(`  ${index + 1}. ${file.oldName} → ${file.newName}`));
      });
    }
    
    if (errors.length > 0) {
      console.log(chalk.red('\n❌ 重命名失败的文件:'));
      errors.forEach((error, index) => {
        console.log(chalk.red(`  ${index + 1}. ${error.file}: ${error.error}`));
      });
    }
    
    if (totalRenamed > 0) {
      console.log(chalk.green(`\n🎉 前缀同步完成！成功更新 ${totalRenamed} 个文件为 "${newPrefix}-" 前缀`));
    } else {
      console.log(chalk.yellow('\n📝 所有文件前缀已是最新状态，无需更新'));
    }
  }

  /**
   * 更新文件内部的引用关系（import语句、类名等）
   */
  async updateFileReferences(newPrefix) {
    console.log(chalk.blue('\n🔗 开始更新文件内部引用关系...'));
    
    const allDirs = ['server', 'backend', 'core', 'utils', 'config', 'src'];
    const codeExtensions = ['.ts', '.js', '.tsx', '.jsx'];
    let updatedFiles = 0;
    
    for (const dir of allDirs) {
      const dirPath = path.join(process.cwd(), dir);
      if (fs.existsSync(dirPath)) {
        console.log(chalk.gray(`  📁 更新目录: ${dir}/`));
        const files = await this.scanDirectoryRecursively(dirPath);
        
        for (const filePath of files) {
          const fileName = path.basename(filePath);
          const fileExt = codeExtensions.find(ext => fileName.endsWith(ext));
          
          if (fileExt) {
            try {
              const content = fs.readFileSync(filePath, 'utf8');
              let updatedContent = content;
              let hasChanges = false;
              
              // 更新 import 语句中的文件名引用
              const importRegex = /import\s+.*?from\s+['"`]([^'"`]*?)(['"`])/g;
              updatedContent = updatedContent.replace(importRegex, (match, importPath, quote) => {
                // 检查是否是相对路径且包含后端文件
                if (importPath.startsWith('./') || importPath.startsWith('../')) {
                  const pathParts = importPath.split('/');
                  const lastPart = pathParts[pathParts.length - 1];
                  
                  // 检查是否是后端文件名模式
                  const backendFilePattern = /^([A-Za-z0-9]+)-(.*\.(controller|service|module|entity|dto|guard|middleware|interceptor|resolver|repository))$/;
                  const match = lastPart.match(backendFilePattern);
                  
                  if (match && match[1] !== newPrefix) {
                    const newFileName = `${newPrefix}-${match[2]}`;
                    const newImportPath = pathParts.slice(0, -1).concat(newFileName).join('/');
                    hasChanges = true;
                    console.log(chalk.yellow(`    🔄 更新import: ${lastPart} → ${newFileName}`));
                    return `import ${match[0].replace(importPath, newImportPath)}`;
                  }
                }
                return match;
              });
              
              // 更新类名引用（如果类名包含前缀）
              const classNameRegex = /\b([A-Za-z0-9]+)(Controller|Service|Module|Entity|Dto|Guard|Middleware|Interceptor|Resolver|Repository)\b/g;
              updatedContent = updatedContent.replace(classNameRegex, (match, prefix, suffix) => {
                // 检查是否是旧前缀且不是新前缀
                if (prefix !== newPrefix && prefix.match(/^[A-Z][a-z]*$/)) {
                  hasChanges = true;
                  console.log(chalk.yellow(`    🔄 更新类名: ${match} → ${newPrefix}${suffix}`));
                  return `${newPrefix}${suffix}`;
                }
                return match;
              });
              
              // 如果有变更，写入文件
              if (hasChanges) {
                fs.writeFileSync(filePath, updatedContent, 'utf8');
                updatedFiles++;
                console.log(chalk.green(`    ✅ 已更新: ${path.relative(process.cwd(), filePath)}`));
              }
              
            } catch (error) {
              console.log(chalk.red(`    ❌ 更新失败: ${fileName} - ${error.message}`));
            }
          }
        }
      }
    }
    
    if (updatedFiles > 0) {
      console.log(chalk.green(`\n🎉 成功更新 ${updatedFiles} 个文件的内部引用！`));
    } else {
      console.log(chalk.yellow('\n📝 未发现需要更新的引用关系'));
    }
  }

  /**
   * 递归扫描目录中的所有文件
   */
  async scanDirectoryRecursively(dirPath) {
    const files = [];
    
    const scanDir = (currentPath) => {
      const items = fs.readdirSync(currentPath);
      
      for (const item of items) {
        const itemPath = path.join(currentPath, item);
        const stat = fs.statSync(itemPath);
        
        if (stat.isDirectory()) {
          // 跳过 node_modules 和 .git 等目录
          if (!['node_modules', '.git', '.trae', 'dist', 'build'].includes(item)) {
            scanDir(itemPath);
          }
        } else if (stat.isFile()) {
          files.push(itemPath);
        }
      }
    };
    
    scanDir(dirPath);
    return files;
  }

  /**
   * 步骤8: 配置项目规则文件
   */
  async step8_ConfigureProjectRules() {
    this.updateStepStatus(8, 'running');
    console.log(chalk.blue('\n📝 步骤8: 配置项目规则文件...'));
    
    const projectRulesPath = path.join(process.cwd(), 'project_rules.md');
    
    if (fs.existsSync(projectRulesPath)) {
      console.log(chalk.green('✅ project_rules.md 文件已存在，跳过配置'));
    } else {
      console.log(chalk.yellow('📝 project_rules.md 文件不存在，需要创建...'));
      
      const choices = [
        { name: '✅ 创建项目规则文件', value: 'create' },
        { name: '❌ 跳过项目规则配置', value: 'skip' },
        { name: '🔙 返回上一步', value: 'RETURN_PREVIOUS' }
      ];

      const answer = await inquirer.prompt([{
        type: 'list',
        name: 'createRules',
        message: '是否创建项目规则文件？',
        choices: choices
      }]);

      if (answer.createRules === 'RETURN_PREVIOUS') {
        await this.step6_SelectDatabase();
        return;
      }

      if (answer.createRules === 'create') {
        await this.createProjectRulesFile(projectRulesPath);
      } else {
        console.log(chalk.yellow('⚠️  跳过项目规则文件创建，建议稍后手动创建'));
      }
    }
    
    this.updateStepStatus(8, 'completed');
  }

  /**
   * 步骤9: 系统自检
   */
  async step9_SystemSelfCheck() {
    this.updateStepStatus(9, 'running');
    console.log(chalk.blue('\n🔍 步骤9: 系统自检...'));
    
    const checks = [
      { name: '检查Node.js环境', check: () => execSync('node --version', { encoding: 'utf8' }) },
      { name: '检查npm环境', check: () => execSync('npm --version', { encoding: 'utf8' }) },
      { name: '检查项目配置文件', check: () => this.checkConfigFiles() },
      { name: '检查核心模块', check: () => this.checkCoreModules() },
      { name: '检查权限设置', check: () => this.checkPermissions() }
    ];
    
    for (const checkItem of checks) {
      try {
        console.log(chalk.yellow(`  正在${checkItem.name}...`));
        await checkItem.check();
        console.log(chalk.green(`  ✅ ${checkItem.name}通过`));
      } catch (error) {
        console.log(chalk.red(`  ❌ ${checkItem.name}失败: ${error.message}`));
        throw new Error(`系统自检失败: ${checkItem.name}`);
      }
    }
    
    console.log(chalk.green('✅ 系统自检完成，所有检查项通过'));
    this.updateStepStatus(9, 'completed');
  }

  /**
   * 步骤10: 启动智能体检测工具
   */
  async step10_StartAgent() {
    this.updateStepStatus(10, 'running');
    console.log(chalk.blue('\n🤖 步骤10: 启动智能体代码规范检测工具...'));
    
    try {
      // 启动智能体
      console.log(chalk.yellow('正在启动智能体...'));
      
      const choices = [
        { name: '✅ 立即启动智能体检测工具', value: 'start' },
        { name: '❌ 跳过智能体启动', value: 'skip' },
        { name: '🔙 返回上一步', value: 'RETURN_PREVIOUS' }
      ];

      const answer = await inquirer.prompt([{
        type: 'list',
        name: 'startAgent',
        message: '是否启动智能体检测工具？',
        choices: choices
      }]);

      if (answer.startAgent === 'RETURN_PREVIOUS') {
        await this.step8_ConfigureProjectRules();
        return;
      }

      if (answer.startAgent === 'start') {
        console.log(chalk.yellow('🚀 正在启动智能体检测工具...'));
        
        // 异步启动，不阻塞当前进程
        const agentProcess = spawn('node', ['utils/ai-bootstrap.js'], {
          stdio: 'inherit',
          detached: true
        });
        
        agentProcess.unref();
        console.log(chalk.green('✅ 智能体检测工具已在后台启动'));
      } else {
        console.log(chalk.yellow('⚠️  跳过智能体启动，可稍后手动执行: npm run start'));
      }
      
      this.updateStepStatus(10, 'completed');
    } catch (error) {
      this.updateStepStatus(10, 'failed');
      console.log(chalk.red(`❌ 智能体启动失败: ${error.message}`));
      console.log(chalk.yellow('💡 可稍后手动执行: npm run start'));
    }
  }

  /**
   * 显示完成信息
   */
  async showCompletion() {
    console.log(chalk.green('\n🎉 一键安装完成！'));
    console.log(chalk.cyan('=================================================='));
    
    console.log(chalk.yellow('📋 安装摘要:'));
    
    // 安全获取语言信息
    const languageName = this.projectConfig.language?.name || 
                        this.projectConfig.frontendStack?.language || 
                        this.projectConfig.backendStack?.language || 
                        'TypeScript';
    
    // 安全获取框架信息
    const frameworkName = this.projectConfig.framework || 
                         this.projectConfig.frontendStack?.framework || 
                         this.projectConfig.backendStack?.framework || 
                         '未指定';
    
    // 安全获取后端前缀
    const backendPrefix = this.projectConfig.backendPrefix || 'Alyr';
    
    console.log(chalk.white(`  语言: ${languageName}`));
    console.log(chalk.white(`  框架: ${frameworkName}`));
    console.log(chalk.white(`  后端前缀: ${backendPrefix}`));
    
    console.log(chalk.yellow('\n🚀 快速开始:'));
    console.log(chalk.white('  1. 启动智能体: npm run start'));
    console.log(chalk.white('  2. 查看配置: npm run config'));
    console.log(chalk.white('  3. 运行检测: npm run check'));
    
    console.log(chalk.yellow('\n📚 相关文档:'));
    console.log(chalk.white('  - 配置指南: docs/CONFIG-QUICK-START.md'));
    console.log(chalk.white('  - 框架支持: docs/FRAMEWORK-TRENDS-ANALYSIS.md'));
    console.log(chalk.white('  - 快速开始: docs/PROJECT-QUICK-START.md'));
    
    console.log(chalk.gray('\n版权所有：© 2020-2025 ALYR.NET'));
  }

  /**
   * 智能检测项目中使用的框架
   */
  detectFrameworks(dependencies) {
    const frameworks = [];
    const depKeys = Object.keys(dependencies);
    
    // 前端框架检测
    if (depKeys.includes('react')) frameworks.push('React');
    if (depKeys.includes('vue')) frameworks.push('Vue');
    if (depKeys.includes('@angular/core')) frameworks.push('Angular');
    if (depKeys.includes('svelte')) frameworks.push('Svelte');
    if (depKeys.includes('next')) frameworks.push('Next.js');
    if (depKeys.includes('nuxt')) frameworks.push('Nuxt.js');
    
    // 后端框架检测
    if (depKeys.includes('express')) frameworks.push('Express');
    if (depKeys.includes('@nestjs/core')) frameworks.push('Nest.js');
    if (depKeys.includes('koa')) frameworks.push('Koa');
    if (depKeys.includes('fastify')) frameworks.push('Fastify');
    
    // UI库检测
    if (depKeys.includes('antd')) frameworks.push('Ant Design');
    if (depKeys.includes('@mui/material')) frameworks.push('Material-UI');
    if (depKeys.includes('element-plus')) frameworks.push('Element Plus');
    if (depKeys.includes('vuetify')) frameworks.push('Vuetify');
    
    // 数据库和ORM检测
    if (depKeys.includes('prisma')) frameworks.push('Prisma');
    if (depKeys.includes('typeorm')) frameworks.push('TypeORM');
    if (depKeys.includes('sequelize')) frameworks.push('Sequelize');
    if (depKeys.includes('mongoose')) frameworks.push('Mongoose');
    
    return frameworks;
  }

  /**
   * 应用检测到的配置
   */
  applyDetectedConfiguration(frameworks, dependencies = {}) {
    console.log(chalk.cyan('\n🎯 正在应用检测到的配置...'));
    
    // 确保dependencies是一个对象
    if (!dependencies || typeof dependencies !== 'object') {
      dependencies = {};
    }
    
    // 自动设置架构类型
    if (frameworks.includes('Next.js') || frameworks.includes('Nuxt.js')) {
      this.projectConfig.architecture = 'Full-Stack Framework';
    } else if (frameworks.includes('React') || frameworks.includes('Vue') || frameworks.includes('Angular')) {
      if (frameworks.includes('Express') || frameworks.includes('Nest.js') || frameworks.includes('Koa')) {
        this.projectConfig.architecture = 'SPA + API';
      } else {
        this.projectConfig.architecture = 'Frontend Only';
      }
    }
    
    // 自动设置前端栈
    if (frameworks.includes('React')) {
      this.projectConfig.frontendStack = {
        language: 'TypeScript',
        framework: frameworks.includes('Next.js') ? 'Next.js' : 'React'
      };
    } else if (frameworks.includes('Vue')) {
      this.projectConfig.frontendStack = {
        language: 'TypeScript',
        framework: frameworks.includes('Nuxt.js') ? 'Nuxt.js' : 'Vue 3'
      };
    } else if (frameworks.includes('Angular')) {
      this.projectConfig.frontendStack = {
        language: 'TypeScript',
        framework: 'Angular'
      };
    }
    
    // 自动设置后端栈
    if (frameworks.includes('Nest.js')) {
      this.projectConfig.backendStack = {
        language: 'TypeScript',
        framework: 'Nest.js'
      };
    } else if (frameworks.includes('Express')) {
      this.projectConfig.backendStack = {
        language: dependencies && dependencies.typescript ? 'TypeScript' : 'JavaScript',
        framework: 'Express'
      };
    } else if (frameworks.includes('Koa')) {
      this.projectConfig.backendStack = {
        language: dependencies && dependencies.typescript ? 'TypeScript' : 'JavaScript',
        framework: 'Koa'
      };
    }
    
    // 自动设置UI组件库
    if (frameworks.includes('Ant Design')) {
      this.projectConfig.uiComponents = { name: 'Ant Design', packages: ['antd'] };
    } else if (frameworks.includes('Material-UI')) {
      this.projectConfig.uiComponents = { name: 'Material-UI', packages: ['@mui/material'] };
    } else if (frameworks.includes('Element Plus')) {
      this.projectConfig.uiComponents = { name: 'Element Plus', packages: ['element-plus'] };
    }
    
    // 自动设置ORM
    if (frameworks.includes('Prisma')) {
      this.projectConfig.orm = { name: 'Prisma', packages: ['prisma', '@prisma/client'] };
    } else if (frameworks.includes('TypeORM')) {
      this.projectConfig.orm = { name: 'TypeORM', packages: ['typeorm'] };
    } else if (frameworks.includes('Sequelize')) {
      this.projectConfig.orm = { name: 'Sequelize', packages: ['sequelize'] };
    } else if (frameworks.includes('Mongoose')) {
      this.projectConfig.orm = { name: 'Mongoose', packages: ['mongoose'] };
    }
    
    console.log(chalk.green('✅ 配置应用完成，将跳过相关选择步骤'));
  }

  /**
   * 分析项目结构
   */
  analyzeProjectStructure() {
    const structure = {
      type: 'Unknown',
      suggestions: []
    };
    
    const hasPublic = fs.existsSync('./public');
    const hasSrc = fs.existsSync('./src');
    const hasPages = fs.existsSync('./pages');
    const hasComponents = fs.existsSync('./components') || fs.existsSync('./src/components');
    const hasServer = fs.existsSync('./server') || fs.existsSync('./backend');
    const hasApi = fs.existsSync('./api') || fs.existsSync('./src/api');
    
    if (hasPages && hasPublic) {
      structure.type = 'Next.js/Nuxt.js Project';
    } else if (hasSrc && hasComponents) {
      structure.type = 'React/Vue SPA';
    } else if (hasServer || hasApi) {
      structure.type = 'Backend API Project';
    } else if (hasPublic && hasSrc) {
      structure.type = 'Frontend Project';
    } else {
      structure.type = 'Empty/Custom Project';
      structure.suggestions.push('建议创建标准的项目结构');
    }
    
    if (!fs.existsSync('./README.md')) {
      structure.suggestions.push('建议添加 README.md 文档');
    }
    
    if (!fs.existsSync('./.gitignore')) {
      structure.suggestions.push('建议添加 .gitignore 文件');
    }
    
    return structure;
  }
  getUIComponentOptions() {
    const frontendStack = this.projectConfig.frontendStack;
    
    if (frontendStack && frontendStack.framework && frontendStack.framework.includes('React')) {
      return [
        { name: 'Ant Design', description: '企业级UI设计语言和React组件库', packages: ['antd', '@ant-design/pro-components'] },
        { name: 'Material-UI', description: 'React的Material Design组件库', packages: ['@mui/material', '@emotion/react'] },
        { name: 'Chakra UI', description: '简单、模块化、易用的React组件库', packages: ['@chakra-ui/react', '@emotion/react'] },
        { name: 'React Bootstrap', description: 'Bootstrap的React实现', packages: ['react-bootstrap', 'bootstrap'] },
        { name: 'Arco Design', description: '字节跳动出品的企业级设计系统', packages: ['@arco-design/web-react'] },
        { name: 'Semi Design', description: '抖音前端团队设计系统', packages: ['@douyinfe/semi-ui'] }
      ];
    } else if (frontendStack && frontendStack.framework && frontendStack.framework.includes('Vue')) {
      return [
        { name: 'Element Plus', description: 'Vue 3的桌面端组件库', packages: ['element-plus'] },
        { name: 'Ant Design Vue', description: 'Ant Design的Vue实现', packages: ['ant-design-vue'] },
        { name: 'Vuetify', description: 'Vue的Material Design组件框架', packages: ['vuetify'] },
        { name: 'Naive UI', description: 'Vue 3的组件库', packages: ['naive-ui'] },
        { name: 'Arco Design Vue', description: '字节跳动Vue组件库', packages: ['@arco-design/web-vue'] },
        { name: 'TDesign Vue', description: '腾讯TDesign Vue组件库', packages: ['tdesign-vue-next'] }
      ];
    } else if (frontendStack && frontendStack.framework && frontendStack.framework.includes('Angular')) {
      return [
        { name: 'Angular Material', description: 'Angular的Material Design组件', packages: ['@angular/material', '@angular/cdk'] },
        { name: 'NG-ZORRO', description: 'Ant Design的Angular实现', packages: ['ng-zorro-antd'] },
        { name: 'PrimeNG', description: 'Angular的UI组件套件', packages: ['primeng', 'primeicons'] },
        { name: 'Clarity', description: 'VMware的Angular设计系统', packages: ['@clr/angular', '@clr/ui'] }
      ];
    } else {
      return [
        { name: '无UI框架', description: '使用原生CSS或自定义样式', packages: [] },
        { name: 'Tailwind CSS', description: '实用优先的CSS框架', packages: ['tailwindcss'] },
        { name: 'Bootstrap', description: '流行的CSS框架', packages: ['bootstrap'] }
      ];
    }
  }

  /**
   * 获取数据库选项
   */
  getDatabaseOptions() {
    return [
      { name: 'MySQL', value: 'mysql', description: '最流行的关系型数据库', type: 'relational', packages: ['mysql2'] },
      { name: 'PostgreSQL', value: 'postgresql', description: '功能强大的开源关系型数据库', type: 'relational', packages: ['pg'] },
      { name: 'MongoDB', value: 'mongodb', description: '流行的NoSQL文档数据库', type: 'document', packages: ['mongodb'] },
      { name: 'Redis', value: 'redis', description: '内存数据结构存储', type: 'cache', packages: ['redis'] },
      { name: 'SQLite', value: 'sqlite', description: '轻量级嵌入式数据库', type: 'relational', packages: ['sqlite3'] },
      { name: 'MariaDB', value: 'mariadb', description: 'MySQL的开源分支', type: 'relational', packages: ['mysql2'] },
      { name: 'Oracle', value: 'oracle', description: '企业级关系型数据库', type: 'relational', packages: ['oracledb'] },
      { name: 'SQL Server', value: 'sqlserver', description: '微软的关系型数据库', type: 'relational', packages: ['mssql'] }
    ];
  }

  /**
   * 获取ORM选项
   */
  getORMOptions(backendStack) {
    // 安全处理backendStack参数，支持对象和字符串格式
    let backendLanguage = '';
    let backendFramework = '';
    
    if (typeof backendStack === 'object' && backendStack !== null) {
      backendLanguage = backendStack.language || '';
      backendFramework = backendStack.framework || '';
    } else if (typeof backendStack === 'string') {
      backendLanguage = backendStack;
    }
    
    // 检查是否为Node.js相关技术栈
    if (backendLanguage.includes('Node.js') || backendFramework.includes('Express') || 
        backendFramework.includes('Nest.js') || backendFramework.includes('Koa') ||
        backendLanguage.includes('JavaScript') || backendLanguage.includes('TypeScript')) {
      return [
        { name: 'Prisma', value: 'prisma', description: '现代化的Node.js和TypeScript ORM', packages: ['prisma', '@prisma/client'] },
        { name: 'TypeORM', value: 'typeorm', description: 'TypeScript和JavaScript的ORM', packages: ['typeorm'] },
        { name: 'Sequelize', value: 'sequelize', description: 'Node.js的Promise ORM', packages: ['sequelize'] },
        { name: 'Mongoose', value: 'mongoose', description: 'MongoDB的对象建模工具', packages: ['mongoose'] },
        { name: 'Knex.js', value: 'knex', description: 'SQL查询构建器', packages: ['knex'] }
      ];
    } else if (backendLanguage.includes('Java')) {
      return [
        { name: 'MyBatis', value: 'mybatis', description: 'Java持久层框架', packages: [] },
        { name: 'Hibernate', value: 'hibernate', description: 'Java ORM框架', packages: [] },
        { name: 'JPA', value: 'jpa', description: 'Java持久化API', packages: [] },
        { name: 'Spring Data JPA', value: 'spring-data-jpa', description: 'Spring的JPA实现', packages: [] }
      ];
    } else if (backendLanguage.includes('Python')) {
      return [
        { name: 'Django ORM', value: 'django-orm', description: 'Django内置ORM', packages: [] },
        { name: 'SQLAlchemy', value: 'sqlalchemy', description: 'Python SQL工具包和ORM', packages: ['sqlalchemy'] },
        { name: 'Peewee', value: 'peewee', description: '轻量级Python ORM', packages: ['peewee'] },
        { name: 'Tortoise ORM', value: 'tortoise-orm', description: '异步Python ORM', packages: ['tortoise-orm'] }
      ];
    } else if (backendLanguage.includes('Go')) {
      return [
        { name: 'GORM', value: 'gorm', description: 'Go的ORM库', packages: [] },
        { name: 'Ent', value: 'ent', description: 'Facebook的Go实体框架', packages: [] },
        { name: 'Xorm', value: 'xorm', description: 'Go的ORM引擎', packages: [] }
      ];
    } else if (backendLanguage.includes('C#')) {
      return [
        { name: 'Entity Framework', value: 'entity-framework', description: '.NET的ORM框架', packages: [] },
        { name: 'Dapper', value: 'dapper', description: '.NET的微型ORM', packages: [] },
        { name: 'NHibernate', value: 'nhibernate', description: '.NET的ORM框架', packages: [] }
      ];
    } else if (backendLanguage.includes('PHP')) {
      return [
        { name: 'Eloquent', value: 'eloquent', description: 'Laravel的ORM', packages: [] },
        { name: 'Doctrine', value: 'doctrine', description: 'PHP的ORM和DBAL', packages: [] },
        { name: 'Propel', value: 'propel', description: 'PHP的ORM', packages: [] }
      ];
    } else if (backendLanguage.includes('Ruby')) {
      return [
        { name: 'Active Record', value: 'active-record', description: 'Rails的ORM', packages: [] },
        { name: 'Sequel', value: 'sequel', description: 'Ruby的数据库工具包', packages: [] },
        { name: 'DataMapper', value: 'datamapper', description: 'Ruby的ORM', packages: [] }
      ];
    }
    
    // 默认返回Node.js的ORM选项（因为这是最常用的）
    return [
      { name: 'Prisma', value: 'prisma', description: '现代化的Node.js和TypeScript ORM', packages: ['prisma', '@prisma/client'] },
      { name: 'TypeORM', value: 'typeorm', description: 'TypeScript和JavaScript的ORM', packages: ['typeorm'] },
      { name: 'Sequelize', value: 'sequelize', description: 'Node.js的Promise ORM', packages: ['sequelize'] },
      { name: 'Mongoose', value: 'mongoose', description: 'MongoDB的对象建模工具', packages: ['mongoose'] }
    ];
  }

  /**
   * 设置框架依赖
   */
  setFrameworkDependencies() {
    let dependencies = [];
    let devDependencies = [];
    
    // 前端依赖
    if (this.projectConfig.frontendStack) {
      const frontend = this.projectConfig.frontendStack;
      
      if (frontend.framework === 'React') {
        dependencies.push('react', 'react-dom', 'react-router-dom');
        devDependencies.push('@types/react', '@types/react-dom', 'vite', '@vitejs/plugin-react');
      } else if (frontend.framework === 'Vue 3') {
        dependencies.push('vue', 'vue-router', 'pinia');
        devDependencies.push('@vitejs/plugin-vue', 'vite', 'typescript');
      } else if (frontend.framework === 'Angular') {
        dependencies.push('@angular/core', '@angular/common', '@angular/router');
        devDependencies.push('@angular/cli', 'typescript');
      } else if (frontend.framework === 'Next.js') {
        dependencies.push('next', 'react', 'react-dom');
        devDependencies.push('@types/react', '@types/react-dom', 'typescript');
      } else if (frontend.framework === 'Nuxt.js') {
        dependencies.push('nuxt', 'vue');
        devDependencies.push('typescript');
      }
    }
    
    // 后端依赖
    if (this.projectConfig.backendStack) {
      const backend = this.projectConfig.backendStack;
      
      if (backend.framework === 'Express') {
        dependencies.push('express', 'cors', 'helmet', 'morgan');
        devDependencies.push('nodemon', '@types/express');
      } else if (backend.framework === 'Nest.js') {
        dependencies.push('@nestjs/core', '@nestjs/common', '@nestjs/platform-express');
        devDependencies.push('@nestjs/cli');
      } else if (backend.framework === 'Koa') {
        dependencies.push('koa', 'koa-router', 'koa-cors');
        devDependencies.push('@types/koa');
      }
      
      if (backend.language === 'TypeScript') {
        devDependencies.push('@types/node', 'typescript', 'ts-node');
      }
    }
    
    // UI组件库依赖
    if (this.projectConfig.uiComponents && this.projectConfig.uiComponents.packages) {
      dependencies.push(...this.projectConfig.uiComponents.packages);
    }
    
    // 数据库依赖
    if (this.projectConfig.database && this.projectConfig.database.packages) {
      dependencies.push(...this.projectConfig.database.packages);
    }
    
    // ORM依赖
    if (this.projectConfig.orm && this.projectConfig.orm.packages) {
      dependencies.push(...this.projectConfig.orm.packages);
    }
    
    // 设置为正确的结构
    this.projectConfig.dependencies = {
      production: [...new Set(dependencies)], // 去重
      development: [...new Set(devDependencies)] // 去重
    };
  }

  /**
   * 更新配置文件
   */
  async updateConfigFiles() {
    const configPath = path.join(__dirname, '../config/unified-data-config.json');
    
    try {
      const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
      
      // 更新后端前缀
      if (config.fileNaming && config.fileNaming.backend) {
        config.fileNaming.backend.prefix = this.projectConfig.backendPrefix || 'Alyr';
      }
      
      // 更新项目信息 - 添加安全检查
      if (config.project) {
        // 安全获取语言信息
        const languageValue = this.projectConfig.language?.value || 
                             this.projectConfig.frontendStack?.language || 
                             this.projectConfig.backendStack?.language || 
                             'TypeScript';
        
        // 安全获取框架信息
        const frameworkValue = this.projectConfig.framework || 
                              this.projectConfig.frontendStack?.framework || 
                              this.projectConfig.backendStack?.framework || 
                              '未指定';
        
        config.project.language = languageValue;
        config.project.framework = frameworkValue;
      }
      
      fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
      console.log(chalk.green('✅ 配置文件已更新'));
    } catch (error) {
      console.log(chalk.yellow(`⚠️  配置文件更新失败: ${error.message}`));
    }
  }

  /**
   * 创建项目规则文件
   */
  async createProjectRulesFile(filePath) {
    // 安全获取配置信息，避免null引用错误
    const languageName = this.projectConfig.language?.name || 
                        this.projectConfig.frontendStack?.language || 
                        this.projectConfig.backendStack?.language || 
                        'TypeScript';
    
    const frameworkName = this.projectConfig.framework || 
                         this.projectConfig.frontendStack?.framework || 
                         this.projectConfig.backendStack?.framework || 
                         '未指定';
    
    const backendPrefix = this.projectConfig.backendPrefix || 'Alyr';
    
    const template = `# 项目开发规范

## 基本信息
- 项目语言: ${languageName}
- 使用框架: ${frameworkName}
- 后端前缀: ${backendPrefix}

## 代码规范
1. 文件命名规范
   - 后端文件: ${backendPrefix}-{模块名}.{类型}.ts
   - 前端组件: PascalCase命名
   - 工具函数: camelCase命名

2. 代码风格
   - 使用TypeScript
   - 遵循ESLint规则
   - 统一使用Prettier格式化

## 开发流程
1. 功能开发前先创建分支
2. 代码提交前运行检测工具
3. 通过Code Review后合并

## 注意事项
- 禁止直接修改主分支
- 所有API接口需要添加错误处理
- 代码必须符合ESLint规范

---
生成时间: ${new Date().toISOString()}
生成工具: Builder.Alyr.Net V4.2.3
`;
    
    fs.writeFileSync(filePath, template);
    console.log(chalk.green('✅ project_rules.md 文件已创建'));
  }

  /**
   * 检查配置文件
   */
  checkConfigFiles() {
    const requiredFiles = [
      'config/unified-data-config.json',
      'package.json',
      'utils/ai-bootstrap.js'
    ];
    
    for (const file of requiredFiles) {
      const filePath = path.join(__dirname, '..', file);
      if (!fs.existsSync(filePath)) {
        throw new Error(`缺少必要文件: ${file}`);
      }
    }
    
    return true;
  }

  /**
   * 检查核心模块
   */
  checkCoreModules() {
    const coreModules = [
      'core/ai-rules-checker.js',
      'core/start.js',
      'utils/smart-install.js'
    ];
    
    for (const module of coreModules) {
      const modulePath = path.join(__dirname, '..', module);
      if (!fs.existsSync(modulePath)) {
        throw new Error(`缺少核心模块: ${module}`);
      }
    }
    
    return true;
  }

  /**
   * 检查权限设置
   */
  checkPermissions() {
    // 检查当前目录的读写权限
    try {
      const testFile = path.join(__dirname, '.permission_test');
      fs.writeFileSync(testFile, 'test');
      fs.unlinkSync(testFile);
      return true;
    } catch (error) {
      throw new Error('当前目录没有写入权限');
    }
  }

  /**
   * 更新步骤状态
   */
  updateStepStatus(stepIndex, status) {
    this.setupSteps[stepIndex].status = status;
    const step = this.setupSteps[stepIndex];
    
    const statusIcon = {
      pending: '⏳',
      running: '🔄',
      completed: '✅',
      failed: '❌'
    };
    
    console.log(chalk.gray(`${statusIcon[status]} ${step.name}`));
  }

  /**
   * 询问用户输入
   */
  askQuestion(question) {
    return new Promise((resolve) => {
      this.rl.question(question, (answer) => {
        resolve(answer);
      });
    });
  }

  /**
   * 检测项目架构类型
   */
  detectProjectArchitecture(frameworks, dependencies) {
    // Next.js 或 Nuxt.js 全栈框架
    if (frameworks.includes('Next.js') || frameworks.includes('Nuxt.js')) {
      return 'fullstack';
    }
    
    // 前端 + 后端 API
    const hasFrontend = frameworks.some(f => ['React', 'Vue', 'Angular', 'Svelte'].includes(f));
    const hasBackend = frameworks.some(f => ['Express', 'Nest.js', 'Koa', 'Fastify'].includes(f));
    
    if (hasFrontend && hasBackend) {
      return 'spa-api';
    }
    
    // 纯后端 API
    if (hasBackend && !hasFrontend) {
      return 'api-only';
    }
    
    // 静态站点生成
    if (dependencies.gatsby || dependencies['@nuxt/static']) {
      return 'jamstack';
    }
    
    // 移动应用
    if (dependencies['react-native'] || dependencies['@ionic/react'] || dependencies['@ionic/vue']) {
      return 'mobile';
    }
    
    // 桌面应用
    if (dependencies.electron || dependencies.tauri) {
      return 'desktop';
    }
    
    return null;
  }

  /**
   * 显示自动配置摘要
   */
  showAutoConfigSummary() {
    console.log(chalk.cyan('\n📋 自动配置摘要:'));
    console.log(chalk.white('=================================================='));
    
    if (this.projectConfig.architecture) {
      console.log(chalk.yellow(`🏗️  项目架构: ${this.projectConfig.architecture}`));
    }
    
    if (this.projectConfig.frontendStack) {
      console.log(chalk.yellow(`🎨 前端技术栈: ${this.projectConfig.frontendStack.framework} (${this.projectConfig.frontendStack.language})`));
    }
    
    if (this.projectConfig.backendStack) {
      console.log(chalk.yellow(`⚙️  后端技术栈: ${this.projectConfig.backendStack.framework} (${this.projectConfig.backendStack.language})`));
    }
    
    if (this.projectConfig.uiComponents) {
      console.log(chalk.yellow(`🎭 UI组件库: ${this.projectConfig.uiComponents.name}`));
    }
    
    if (this.projectConfig.database) {
      console.log(chalk.yellow(`🗄️  数据库: ${this.projectConfig.database.name}`));
    }
    
    if (this.projectConfig.orm) {
      console.log(chalk.yellow(`🔗 ORM: ${this.projectConfig.orm.name}`));
    }
    
    console.log(chalk.white('=================================================='));
    console.log(chalk.green('✅ 自动配置已应用，将跳过手动选择步骤'));
  }

  /**
   * 显示快速模板选择
   */
  async showQuickTemplates() {
    console.log(chalk.cyan('\n📋 快速模板选择:'));
    
    const templates = [
      {
        name: '🚀 React + Express 全栈应用',
        value: 'react-express',
        description: 'React前端 + Express后端 + MongoDB'
      },
      {
        name: '⚡ Vue + Nest.js 企业级应用',
        value: 'vue-nestjs',
        description: 'Vue 3前端 + Nest.js后端 + PostgreSQL'
      },
      {
        name: '🎯 Next.js 全栈框架',
        value: 'nextjs-fullstack',
        description: 'Next.js + TypeScript + Prisma'
      },
      {
        name: '📱 React Native 移动应用',
        value: 'react-native',
        description: 'React Native + Expo + Firebase'
      },
      {
        name: '🖥️ Electron 桌面应用',
        value: 'electron-app',
        description: 'Electron + React + SQLite'
      },
      {
        name: '🔙 返回手动配置',
        value: 'manual'
      }
    ];

    const templateChoice = await inquirer.prompt([{
      type: 'list',
      name: 'template',
      message: '选择快速模板:',
      choices: templates.map(t => ({
        name: t.description ? `${t.name}\n  ${chalk.gray(t.description)}` : t.name,
        value: t.value
      }))
    }]);

    if (templateChoice.template !== 'manual') {
      this.applyQuickTemplate(templateChoice.template);
      this.projectConfig.autoConfigured = true;
      console.log(chalk.green(`✅ 已应用模板: ${templateChoice.template}`));
    }
  }

  /**
   * 应用快速模板
   */
  applyQuickTemplate(templateName) {
    const templates = {
      'react-express': {
        architecture: 'spa-api',
        frontendStack: { language: 'TypeScript', framework: 'React' },
        backendStack: { language: 'TypeScript', framework: 'Express' },
        uiComponents: { name: 'Ant Design', packages: ['antd'] },
        database: { name: 'MongoDB', packages: ['mongodb'] },
        orm: { name: 'Mongoose', packages: ['mongoose'] }
      },
      'vue-nestjs': {
        architecture: 'spa-api',
        frontendStack: { language: 'TypeScript', framework: 'Vue 3' },
        backendStack: { language: 'TypeScript', framework: 'Nest.js' },
        uiComponents: { name: 'Element Plus', packages: ['element-plus'] },
        database: { name: 'PostgreSQL', packages: ['pg'] },
        orm: { name: 'TypeORM', packages: ['typeorm'] }
      },
      'nextjs-fullstack': {
        architecture: 'fullstack',
        frontendStack: { language: 'TypeScript', framework: 'Next.js' },
        backendStack: { language: 'TypeScript', framework: 'Next.js API' },
        uiComponents: { name: 'Material-UI', packages: ['@mui/material'] },
        database: { name: 'PostgreSQL', packages: ['pg'] },
        orm: { name: 'Prisma', packages: ['prisma'] }
      },
      'react-native': {
        architecture: 'mobile',
        frontendStack: { language: 'TypeScript', framework: 'React Native' },
        uiComponents: { name: 'NativeBase', packages: ['native-base'] },
        database: { name: 'Firebase', packages: ['firebase'] }
      },
      'electron-app': {
        architecture: 'desktop',
        frontendStack: { language: 'TypeScript', framework: 'React' },
        uiComponents: { name: 'Ant Design', packages: ['antd'] },
        database: { name: 'SQLite', packages: ['sqlite3'] }
      }
    };

    const template = templates[templateName];
    if (template) {
      Object.assign(this.projectConfig, template);
      this.projectConfig.backendPrefix = 'Alyr'; // 默认前缀
    }
  }

  /**
   * 为所有选择步骤添加跳过选项
   */
  addSkipOption(choices, stepName) {
    return [
      ...choices,
      new inquirer.Separator(),
      { name: '⏭️ 跳过此步骤', value: 'SKIP_STEP' },
      { name: '🔙 返回上一步', value: 'RETURN_PREVIOUS' }
    ];
  }

  /**
   * 处理跳过步骤逻辑
   */
  handleSkipStep(stepName) {
    console.log(chalk.yellow(`⏭️ 跳过${stepName}，使用默认配置`));
    
    // 根据步骤设置默认值
    switch (stepName) {
      case '前端技术栈':
        this.projectConfig.frontendStack = { language: 'TypeScript', framework: 'React' };
        break;
      case '后端技术栈':
        this.projectConfig.backendStack = { language: 'TypeScript', framework: 'Express' };
        break;
      case 'UI组件库':
        this.projectConfig.uiComponents = { name: 'Ant Design', packages: ['antd'] };
        break;
      case '数据库':
        this.projectConfig.database = { name: 'MongoDB', packages: ['mongodb'] };
        this.projectConfig.orm = { name: 'Mongoose', packages: ['mongoose'] };
        break;
    }
  }

  /**
   * 保存用户选择配置到文件
   */
  async saveUserChoices() {
    try {
      const configDir = path.join(__dirname, '..', 'config');
      if (!fs.existsSync(configDir)) {
        fs.mkdirSync(configDir, { recursive: true });
      }

      const setupChoicesPath = path.join(configDir, 'setup-choices.json');
      
      // 构建用户选择配置
      const userChoices = {
        projectName: this.projectConfig.projectName || 'Builder.Alyr.Net Project',
        architecture: this.projectConfig.architecture,
        frontend: this.projectConfig.frontendStack?.framework?.toLowerCase(),
        backend: this.projectConfig.backendStack?.framework?.toLowerCase(),
        database: this.projectConfig.database?.name?.toLowerCase(),
        uiComponents: this.projectConfig.uiComponents?.name?.toLowerCase().replace(/\s+/g, '-'),
        orm: this.projectConfig.orm?.name?.toLowerCase(),
        backendPrefix: this.projectConfig.backendPrefix || 'Builder.Alyr.Net',
        useTypeScript: this.projectConfig.frontendStack?.language === 'TypeScript',
        environment: process.env.NODE_ENV || 'development',
        timestamp: new Date().toISOString(),
        autoConfigured: this.projectConfig.autoConfigured || false,
        detectedEnvironment: this.projectConfig.detectedEnvironment
      };

      // 保存配置文件
      fs.writeFileSync(setupChoicesPath, JSON.stringify(userChoices, null, 2), 'utf8');
      console.log(chalk.green(`✅ 用户选择已保存到: ${setupChoicesPath}`));
      
      return userChoices;
    } catch (error) {
      console.error(chalk.red('❌ 保存用户选择失败:'), error);
      throw error;
    }
  }

  /**
   * 触发配置同步
   */
  async triggerConfigSync() {
    try {
      console.log(chalk.blue('\n🔄 开始配置同步...'));
      
      // 动态导入配置同步管理器
      const ConfigSyncManager = require('../core/config-sync-manager');
      const syncManager = new ConfigSyncManager();
      
      // 执行配置同步
      await syncManager.executeFullSync();
      
      console.log(chalk.green('✅ 配置同步完成！智能体已配置为使用您选择的技术栈。'));
      
    } catch (error) {
      console.error(chalk.red('❌ 配置同步失败:'), error);
      console.log(chalk.yellow('⚠️  您可以稍后手动运行配置同步：'));
      console.log(chalk.gray('   node core/config-sync-manager.js'));
    }
  }

  /**
   * 完成安装流程
   */
  async completeSetup() {
    try {
      console.log(chalk.blue('\n🎯 完成安装流程...'));
      
      // 1. 保存用户选择
      const userChoices = await this.saveUserChoices();
      
      // 2. 触发配置同步
      await this.triggerConfigSync();
      
      // 3. 显示完成信息
      console.log(chalk.green('\n🎉 一键安装完成！'));
      console.log(chalk.cyan('\n📋 安装摘要:'));
      console.log(chalk.white('=================================================='));
      console.log(chalk.yellow(`🏗️  项目架构: ${userChoices.architecture}`));
      console.log(chalk.yellow(`🎨 前端框架: ${userChoices.frontend}`));
      console.log(chalk.yellow(`⚙️  后端框架: ${userChoices.backend}`));
      console.log(chalk.yellow(`🗄️  数据库: ${userChoices.database}`));
      console.log(chalk.yellow(`🎭 UI组件库: ${userChoices.uiComponents}`));
      console.log(chalk.yellow(`🏷️  后端前缀: ${userChoices.backendPrefix}`));
      console.log(chalk.white('=================================================='));
      
      console.log(chalk.cyan('\n🚀 下一步操作:'));
      console.log(chalk.gray('   1. 运行智能体检测工具进行代码规范检查'));
      console.log(chalk.gray('   2. 使用自动修复功能优化代码'));
      console.log(chalk.gray('   3. 开始项目开发'));
      
      console.log(chalk.cyan('\n🔧 可用命令:'));
      console.log(chalk.gray('   npm run dev          # 启动开发服务器'));
      console.log(chalk.gray('   npm run build        # 构建项目'));
      console.log(chalk.gray('   npm run lint          # 代码检查'));
      console.log(chalk.gray('   npm run fix           # 自动修复'));
      
    } catch (error) {
      console.error(chalk.red('❌ 完成安装流程失败:'), error);
    }
  }
}

// 如果直接运行此文件
if (require.main === module) {
  const setup = new OneClickSetup();
  setup.start().catch(console.error);
}

module.exports = OneClickSetup;